var ZYRequestClient = require("../../../../utils/zy-request");
var requestClient;
const app = getApp()
Page({
  data: {
    // 滚动容器的高度
    scrollViewHeight:600,
    // 用户id
    userId:0,
    // 公司id
    companyId:0,
    // 盖章记录查询条件
    stampFileTypeIndex:[0,0],
    sealIndex:0,
    stampUserIndex:0,
    stampSubmitDateIndex:0,
    stampType:0,
    showSealDialog:false,
    showUserDialog:false,
    selectedSeal:null,
    selectStampUser:null,
    // 文件类型
    applyFileTypeList:[],
    // 印章选项
    sealList:[],
    // 盖章人选项
    stampUserList:[],
    // 提交日期选项
    submitDateList:[
      {text:'全部',value:null},
      {text:'近7日',value:7},{text:'近半个月',value:15},
      {text:'近一个月',value:30}
    ],
    // 盖章记录查询参数
    stampParams:{
      userId:null,
      fileType:null,
      sealId:null,
      stampUserId:null,
      duration:null,
      companyId:null,
      stampType:null,
      keyWords:null,
      exportType:0,
      pageNo:0,
    },
    // 盖章记录
    stampRecordList:[],
    // 是否为管理员
    hasAdmin:false,
    showExportAction:false,
    exportActionButtons:[{text:'盖章记录',value:'stamp_record'},{text:'申请拍照文件',value:'apply_file'},{text:'盖章拍照文件',value:'stamp_file'}],
    navbarData:{
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '盖章记录', //导航栏 中间的标题
      white:true
     },
     // 导航头的高度
     height: app.globalData.height * 2 + 20
  },
  onLoad() {
    requestClient = new ZYRequestClient();
    var userInfo = wx.getStorageSync('userInfo');
    if(userInfo==''){
      wx.showModal({
        title:'授权登录',
        content:'请授权登录使用更多功能！',
        showCancel:false,
        success(r){
          wx.navigateTo({
            url: '../../../login/index',
          })
        }
      })
      return;
    }
    this.setData({
      userId:userInfo.id,
      stampSearch: this.stampSearch.bind(this),
      hasAdmin:false
    });
    var defaultCompany = wx.getStorageSync('defaultCompany');
    if(defaultCompany == ''){
      this.setData({
        companyId:0
      });
    } else {
      this.setData({
        companyId:defaultCompany.id
      });
    }
    this.setScrollViewHeight();
    this.initData();
  },
  onShow(){
    this.loadStampRecord(false);
  },
  initData(){
    var _this = this;
    _this.loadSealList();
    _this.getContractTypeList();
    _this.getAllUserList();
    
    // 初始化查询参数
    _this.setData({
      'stampParams.userId':_this.data.userId,
      'stampParams.fileType':null,
      'stampParams.sealId':null,
      'stampParams.stampUserId':null,
      'stampParams.companyId':_this.data.companyId,
      'stampParams.duration':null,
      'stampParams.stampType':_this.data.stampType,
      'stampParams.keyWords':null,
      'stampParams.pageNo':0,
    });
    requestClient.checkFunctionPermission(1000,null,function(){
      _this.setData({
        hasAdmin:true,
        'stampParams.hasAdmin':true,
      });
    },function(){
      _this.setData({
        hasAdmin:false,
        'stampParams.hasAdmin':false,
      });
    })
  },
  // 设置滚动容器的高度
  setScrollViewHeight:function(){
    var _this = this;
    // 获取系统信息得到屏幕高度
    wx.getSystemInfo({
      success: function (res) {
        let clientHeight = res.windowHeight;
          _this.setData({
            scrollViewHeight:clientHeight - _this.data.height
          });
      }
    });
  },
  // 获取合同类型
  getContractTypeList(){
    var _this = this;
    requestClient.getContractTypeList(function(res){
      _this.setData({
        fileTypeParentArray:res.data.data.parentList,
        fileTypeChildArray:res.data.data.childList
      });
      _this.setData({
        fileTypeArray:[_this.data.fileTypeParentArray,_this.data.fileTypeChildArray[0]]
      });
      var newFileTypeParentArray = _this.data.fileTypeParentArray;
      newFileTypeParentArray.splice(0,0,'全部');
      var newFileTypeChildArray = res.data.data.childList;
      newFileTypeChildArray.splice(0,0,['全部']);
      _this.setData({
        applyFileTypeList:[newFileTypeParentArray,newFileTypeChildArray[0]]
      });
    })
  },
  // 获取印章列表
  loadSealList(){
    var _this = this;
    requestClient.getSealList2(_this.data.companyId,function(res){
      var seal = { id: null, name:'全部'};
      var sealList = [];
      sealList.push(seal);
      for(var i=0;i<res.data.data.length;i++){
        var data = res.data.data[i];
        sealList.push(data);
      }
      _this.setData({
        sealList:sealList
      });
    });
  },
  // 获取公司下所有用户
  getAllUserList(){
    var _this = this;
    var defaultCompany = wx.getStorageSync('defaultCompany');
    requestClient.getAllUserList(defaultCompany.id,function(res){
      var newUserList = [];
      var defaultUser = {id:null,nickName:'全部'};
      newUserList.push(defaultUser);
      for(var i=0;i< res.data.data.length;i++){
        var user = res.data.data[i];
        // if(user.id == _this.data.userId){
        //   continue;
        // }
        var newUser = {id:user.id,nickName:user.nickName};
        newUserList.push(newUser);
      }
      _this.setData({
        stampUserList:newUserList
      });
    })
  },
  // 加载盖章记录
  loadStampRecord(append){
    var _this = this;
    if(append){
      wx.showLoading({
        title: '加载更多',
        mask:true
      })
    } else {
      wx.showLoading({
        title: '刷新数据',
        mask:true
      })
    }
    requestClient.getStampRecord(_this.data.stampParams,function(res){
      wx.hideLoading({
        success: (res) => {},
      })
      if(res.data.data){
        if(append){
          var stampRecordList = _this.data.stampRecordList.concat(res.data.data);
          _this.setData({
            stampRecordList:stampRecordList
          });
        } else {
          _this.setData({
            stampRecordList:res.data.data
          });
        }
      }
    })
  },
  // 搜索记录
  stampSearch:function(value){
    if(value==''){
      this.setData({
        'stampParams.keyWords':null
      });
    } else {
      this.setData({
        'stampParams.keyWords':value
      });
    }
    this.loadStampRecord(false);
    
    return new Promise((resolve, reject) => {
      setTimeout(() => {
          resolve([])
      }, 200)
    })
  },
  stampSearchClear(e){
    this.setData({
      'stampParams.keyWords':null
    });
    this.loadStampRecord(false);
  },
  // 选择盖章类型
  bindStampType(e){
    this.setData({
      stampType: parseInt(e.currentTarget.dataset.num),
      'stampParams.stampType':parseInt(e.currentTarget.dataset.num)
    });
    this.loadStampRecord(false);
  },
  // 选择文件类型
  changeStampFileType(e){
    this.setData({
      stampFileTypeIndex:e.detail.value
    });
    if(e.detail.value[0] == 0){
      this.setData({
        'stampParams.fileType':null
      });
    } else {
      this.setData({
        'stampParams.fileType':this.data.applyFileTypeList[1][e.detail.value[1]]
      });
    }
    this.loadStampRecord(false);
  },
  changeStampFileTypeColumn(e){
    var _this = this;
    // 如果是第一列则更新第二列的选项
    if(e.detail.column == 0){
      var applyFileTypeList = _this.data.applyFileTypeList;
      applyFileTypeList[1] = _this.data.fileTypeChildArray[e.detail.value];
      _this.setData({
        applyFileTypeList:applyFileTypeList
      });
    }
    var stampFileTypeIndex = _this.data.stampFileTypeIndex;
    stampFileTypeIndex[e.detail.column] = e.detail.value;
    _this.setData({
      stampFileTypeIndex:stampFileTypeIndex
    });
  },
  // 选择印章
  bindShowSelectSeal(e){
    var _this = this;
    _this.setData({
      showSealDialog:true,
    });
  },
  bindSealCheck(e){
    var _this = this;
    _this.setData({
      showSealDialog:false,
    });
    var id = e.detail.value;
    if(!!id){
      var sealList = _this.data.sealList;
      for(var i=0;i<sealList.length;i++){
        if(sealList[i].id == parseInt(e.detail.value)){
          _this.setData({
            selectedSeal:sealList[i]
          });
          break;
        }
      }
    } else {
      _this.setData({
        selectedSeal:null,
      });
    }
    _this.setData({
      'stampParams.sealId':id,
    });
    this.loadStampRecord(false);
  },
  bindClosedSeal(e){
    var _this = this;
    _this.setData({
      showSealDialog:false,
    });
  },
  // 选择盖章人
  bindShowSelectUser(e){
    var _this = this;
    _this.setData({
      showUserDialog:true,
    });
  },
  bindUserCheck(e){
    var _this = this;
    _this.setData({
      showUserDialog:false,
    });
    var id = e.detail.value;
    if(!!id){
      for(var i=0;i<_this.data.stampUserList.length;i++){
        var stampUser = _this.data.stampUserList[i];
        if(stampUser.id == parseInt(id)){
          _this.setData({
            selectStampUser:stampUser,
          });
          break;
        }
      }
    } else {
      _this.setData({
        selectStampUser:null,
      });
    }
    _this.setData({
      'stampParams.stampUserId':id,
    });
    _this.loadStampRecord(false);
  },
  bindClosedUser(e){
    var _this = this;
    _this.setData({
      showUserDialog:false,
    });
  },
  // 选择盖章日期
  bindSelectDateClick(){
    var _this = this;
    _this.setData({
      showDateDialog:true,
    });
  },
  stampSubmitDateConfirm(e){
    var _this = this;
    var sealTimeText = e.detail.text;
    if(sealTimeText==null){
      sealTimeText = "盖章日期";
    }
    _this.setData({
      sealTimeText:sealTimeText,
    });
    _this.setData({
      'stampParams.startTime':e.detail.startTime,
      'stampParams.endTime':e.detail.endTime,
    });
    _this.loadStampRecord(false);
  },
  // 盖章记录上拉刷新
  refreshStampRecordList(e){
    var _this = this;
    _this.setData({
      'stampParams.pageNo':0
    });
    _this.loadStampRecord(false);
  },
  // 盖章记录下拉加载更多数据
  loadMoreStampRecordList(e){
    var _this = this;
    var pageNo = _this.data.stampParams.pageNo;
    pageNo ++;
    _this.setData({
      'stampParams.pageNo':pageNo
    });
    _this.loadStampRecord(true);
  },
  // 查看用印记录详情
  bindStampRecordClick(e){
    var stamprecord = e.currentTarget.dataset.stamprecord;
    // 跳转到盖章记录详情页面
    wx.navigateTo({
      url: '../stamprecorddetail/index?stampRecordId=' + stamprecord.id + '&applyId=' + stamprecord.applyId,
    })
  },
  // 导出盖章记录
  bindExportRecord(e){
    var _this = this;
    if(_this.data.stampType == 0){
      _this.setData({
        showExportAction:true,
      });
      return;
    }
    wx.showModal({
      title:'导出盖章记录',
      content:'您确定要导出查询到的盖章记录吗？',
      success(r){
        if(r.confirm){
          _this.exportStampRecord();
        }
      }
    })
  },
  // 导出选项按钮
  bindExportActionTap(e){
    var _this = this;
    _this.setData({
      showExportAction:false,
    });
    if(e.detail.value == 'stamp_record'){
      _this.exportStampRecord();
    } else if(e.detail.value == 'apply_file'){
      _this.exportApplyFile();
    } else if(e.detail.value == 'stamp_file'){
      _this.exportStampFile();
    }
  },
  exportStampRecord(){
    var _this = this;
    wx.showLoading({
      title: '正在导出...',
    })
    _this.setData({
      "stampParams.exportType":0,
    });
    requestClient.exportStampRecord(_this.data.stampParams,function(res){
      wx.hideLoading({
        success: (res) => {},
      })
      const fs = wx.getFileSystemManager();
      fs.writeFile({
        filePath: wx.env.USER_DATA_PATH + "/盖章记录.xls", // wx.env.USER_DATA_PATH 指定临时文件存入的路径，后面字符串自定义
        data: res.data,
        encoding: "binary", //二进制流文件必须是 binary
        success (res){
          wx.openDocument({ // 打开文档
            filePath: wx.env.USER_DATA_PATH + "/盖章记录.xls",  //拿上面存入的文件路径
            showMenu: true, // 显示右上角菜单
            success: function (res) {
              setTimeout(()=>{wx.hideLoading()},500)
            }
          })
        }
      })
    });
  },
  exportApplyFile(){
    var _this = this;
    _this.setData({
      "stampParams.exportType":1,
    });
    requestClient.exportStampRecord(_this.data.stampParams,function(res){
      wx.showModal({
        title:'操作成功',
        content:'请复制下载地址到浏览器中下载，一次有效',
        confirmText:'复制',
        success(r){
          if(r.confirm){
            wx.setClipboardData({
              data:res.data,
            });
          }
        }
      })
    });
  },
  exportStampFile(){
    var _this = this;
    _this.setData({
      "stampParams.exportType":2,
    });
    requestClient.exportStampRecord(_this.data.stampParams,function(res){
      wx.showModal({
        title:'操作成功',
        content:'请复制下载地址到浏览器中下载，一次有效',
        confirmText:'复制',
        success(r){
          if(r.confirm){
            wx.setClipboardData({
              data:res.data,
            });
          }
        }
      })
    });
  },
  // 跳转盖章拍照
  goStampPhoto(e){
    var applyId = e.currentTarget.dataset.applyid;
    wx.navigateTo({
      url: '../stampphoto/index?applyId=' + applyId,
    })
  }
})